//
//  CourseJudgeViewController.swift
//  ddx0513
//
//  Created by shuijing on 15/7/26.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class CourseJudgeViewController: UITableViewController, PopupDelegate,CWStarRateViewDelegate,UITextViewDelegate, UIGestureRecognizerDelegate, UIAlertViewDelegate{
    
    @IBOutlet weak var learningButton: UIButton!
    @IBOutlet weak var lineView: UIImageView!
    
    var nickNameArr:NSMutableArray = []
    var contextArr:NSMutableArray = []
    var starArr:NSMutableArray = []
    var createtimeArr:NSMutableArray = []
    var totalCount = 0
    var lessonId:Int!
    var starRateView: CWStarRateView?
    var score: CGFloat = 1.0
    var hud: MBProgressHUD?
    var allowCellular = false
    var totalPage = 0
    var pageSize = 18
    var pageNum = 1
    var datas:Int = 4
    var thisPage = 0
    var searchTime: Int64?
    
    func datainit()
    {
        thisPage = 0
        nickNameArr.removeAllObjects()
        contextArr.removeAllObjects()
        createtimeArr.removeAllObjects()
        starArr.removeAllObjects()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.tableFooterView = UIView(frame: CGRectZero)
        
        //下拉刷新
        self.tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            self.datainit()
            self.getData(1)
        })
        self.tableView.header.beginRefreshing()
        
        // Do any additional setup after loading the view.
    }

    func popPlayCheckView() {
        var device : UIDevice = UIDevice.currentDevice()
        var systemVersion = device.systemVersion
        var iosVerion = (systemVersion as NSString).floatValue
        if(iosVerion < 8.0) {
            let alert = UIAlertView(title: "", message: "您不是会员，暂时无法对课程进行评价。", delegate: self, cancelButtonTitle: "取消")
            alert.show()
        } else {
            var alert : UIAlertController = UIAlertController(title: "", message: "您不是会员，暂时无法对课程进行评价。", preferredStyle: UIAlertControllerStyle.Alert)
            
            alert.addAction(UIAlertAction(title: "取消", style:.Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
    
    
    func starRateView(starRateView: CWStarRateView!, scroePercentDidChange newScorePercent: CGFloat) {
        if (DBUtils.mem.loginStatus){
            var storyBoard = UIStoryboard(name: "Popup", bundle: nil)
            var viewController = storyBoard.instantiateViewControllerWithIdentifier("CourseFeedback") as! CourseFeedbackViewController
            viewController.delegate = self
            viewController.score = self.starRateView!.scorePercent
            viewController.lessonId = lessonId
            self.presentPopupViewController(viewController, animated: true, completion: nil)
            self.setPopviewGuesture()
        }
        else
        {
            popPlayCheckView()
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setPopviewGuesture() {
        var fadeview = self.getBlueView()
        var tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismissPopup:"))
        tapRecognizer.numberOfTapsRequired = 1
        tapRecognizer.delegate = self
        fadeview.addGestureRecognizer(tapRecognizer)
    }
    
    //MARK: - 网络回调函数
    
    func getData(pageNum: Int)
    {
        var a: [String: AnyObject] = ["lessonid":lessonId,"pn":pageNum,"ps":pageSize]
        
        if (pageNum > 1) {
            a.updateValue(NSNumber(longLong: self.searchTime!), forKey: "searchtime")
        }
        
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessoonComments() , parameters: a, responseHandler: nil, netErrorHandler: errorHandler, successHandler: judgeTableview, interErrorHandler: interErrorHandler, jsonErrorHandler: errorHandler)
    }
    
    //MARK: - 网络回调函数
    
    func judgeTableview (json: JSON) {
        totalCount = json["totalcount"].int!
        let listNum = json["list"].count

        for (var i = 0;i < listNum; i++ )
        {
            nickNameArr.addObject(json["list"][i]["nickname"].string!)
            let createTime = json["list"][i]["createtime"].int64!
            createtimeArr.addObject(StringUtils.getDateString(Double(createTime), format: "yyyy-MM-dd"))
            contextArr.addObject(json["list"][i]["context"].string!)
            starArr.addObject(json["list"][i]["star"].int!)
        }
        
        thisPage++
        self.tableView.reloadData()
        
        if (self.thisPage == 1) {
            self.tableView.header.endRefreshing()
            self.searchTime = json["searchtime"].int64!
            self.totalPage = Int(ceil(Double(totalCount) / Double(pageSize)))
            
            self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
                self.getData(self.thisPage+1)
            })
            
            if (self.totalPage == self.thisPage) {
                self.tableView.footer.noticeNoMoreData()
            }
        }
        
        if (self.totalPage > self.thisPage) {
            self.tableView.footer.endRefreshing()
        } else {
            self.tableView.footer.noticeNoMoreData()
        }
    }
    
    func errorHandler() {
        if (self.thisPage == 0) {
            self.tableView.header.endRefreshing()
        } else {
            self.tableView.footer.endRefreshing()
        }
        MBHudUtils.showText("加载失败", view: self.view)
    }
    
    func interErrorHandler(retCode: Int, retMsg: String) {
        if (self.thisPage == 0) {
            self.tableView.header.endRefreshing()
        } else {
            self.tableView.footer.endRefreshing()
        }
        MBHudUtils.showText("加载失败", view: self.view)
    }
    
    
    func getJudgeTextHeight(text: NSString) -> CGFloat {
        let width = UIScreen.mainScreen().bounds.size.width - 20
        let size = CGSizeMake(width, 1000)
        
        let font = UIFont.systemFontOfSize(14)
        let tdic = NSDictionary(object: font, forKey: NSFontAttributeName)
        let size2 = text.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, attributes: tdic as [NSObject : AnyObject], context: nil).size
        
        return size2.height + 36
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        
        return starArr.count + 1
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if (indexPath.row == 0) {
            var tableCell = tableView.dequeueReusableCellWithIdentifier("courseJudgeStar") as! UITableViewCell
            
            if (self.starRateView == nil) {
                self.starRateView = CWStarRateView(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width / 2 - 50, 10, 100, 20), numberOfStars: 5)
                self.starRateView?.scorePercent = 0
                self.starRateView!.allowIncompleteStar = false
                self.starRateView!.hasAnimation = false
                self.starRateView?.delegate = self
                tableCell.addSubview(self.starRateView!)
            }
            
            return tableCell
        } else {
            var tableCell:CourseJudgeItem! = tableView.dequeueReusableCellWithIdentifier("courseJudgeDetail") as! CourseJudgeItem
            
            tableCell.judge.text = contextArr.objectAtIndex(indexPath.row - 1) as? String
            
            
            tableCell.nickName.text = nickNameArr.objectAtIndex(indexPath.row - 1) as? String
            
//            var ctime = createtimeArr.objectAtIndex(indexPath.row - 1) as! Int
//            tableCell.createTime.text = StringUtils.getDateString(Double(ctime), format: "yyyy-MM-dd")
            tableCell.createTime.text = createtimeArr.objectAtIndex(indexPath.row - 1) as? String
            
            var starNum = starArr.objectAtIndex(indexPath.row - 1) as! Int
            if(starNum == 0)
            {
                tableCell.starImage.image = UIImage(named: "零星.png")
            }
            else if(starNum == 1)
            {
                tableCell.starImage.image = UIImage(named: "一星.png")
    
            }
            else if(starNum == 2)
            {
                tableCell.starImage.image = UIImage(named: "二星.png")
            }
            else if(starNum == 3)
            {
                tableCell.starImage.image = UIImage(named: "三星.png")
            }
            else if(starNum == 4)
            {
                tableCell.starImage.image = UIImage(named: "四星.png")
            }
            else if(starNum == 5)
            {
                tableCell.starImage.image = UIImage(named: "星级.png")
            }
            
            return tableCell
        }
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if (indexPath.row == 0) {
            return 44
        } else {
            return ViewUtils.heightForLabelString(contextArr.objectAtIndex(indexPath.row - 1) as! NSString, fontSize: 14, width: UIScreen.mainScreen().bounds.size.width - 20) + 36
        }
    }
    
    func dismissPopup(animated: Bool) ->Void {
        // submitData()
        if (self.popupViewController != nil) {
            self.dismissPopupViewControllerAnimated(animated, completion: nil)
            self.tableView.header.beginRefreshing()
        }
    }
    
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
    
}
